package com.example.springboot.demo.controller;

import com.example.springboot.demo.pojo.User;
import com.zengtengpeng.operation.RedissonObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/redisson")
public class RedissonController {

    @Autowired
    private RedissonObject redissonObject;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/test1")
    @ResponseBody
    public String test1() throws InterruptedException {
        return stringRedisTemplate.toString();
    }


    /**
     * 设置值
     *
     * @param user
     * @param request
     * @param response
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/object1")
    @ResponseBody
    public String object1(User user, HttpServletRequest request, HttpServletResponse response) throws InterruptedException {
        User user1 = new User();
        user1.setName("test");
        user1.setAge("123");
        redissonObject.setValue("object1", user1, -1L);

        return "";
    }

    /**
     * 获取值
     *
     * @param user
     * @param request
     * @param response
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/object2")
    @ResponseBody
    public Object object2(User user, HttpServletRequest request, HttpServletResponse response) throws InterruptedException {
        //如果缓存有值从缓存里面读, 否则从接口函数读实时数据存入redis
        redissonObject.getValue("object1", () -> "获取值逻辑", 200213213L);

        return redissonObject.getValue("object1");
    }

    /**
     * 如果对象不存在则设置,否则不设置
     *
     * @param user
     * @param request
     * @param response
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/object3")
    @ResponseBody
    public String object3(User user, HttpServletRequest request, HttpServletResponse response) throws InterruptedException {
        return redissonObject.trySetValue("object1", "object1-2") + "";
    }
}
